const { MongoClient } = require('mongodb');

async function run() {
    const uri = "mongodb://project_text:x5YPShnfGbhkrc2Z@47.99.143.87:27017/project_text?authSource=admin";
    const client = new MongoClient(uri);

    try {
        await client.connect();
        console.log("成功连接到 MongoDB!");

        // 1. 创建数据库
        const db = client.db("newDatabase");

        // 2. 创建集合
        const collection = db.collection("users");

        // 3. 插入文档
        await collection.insertOne({
            name: "张三",
            email: "zhangsan@example.com",
            created: new Date()
        });

        // 4. 查询文档
        const users = await collection.find({}).toArray();
        console.log("所有用户:", users);

        // 5. 更新文档
        await collection.updateOne(
            { name: "张三" },
            { $set: { email: "newemail@example.com" } }
        );

        // 6. 删除文档
        await collection.deleteOne({ name: "张三" });

    } catch (err) {
        console.error("操作失败:", err);
    } finally {
        await client.close();
    }
}

run();